﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using SmartProject.Data;
using SmartProject.Exceptions;

namespace SmartProject
{
    /// <summary>
    /// Helper class to get access to save global preferences unrelated to any
    /// Business rule.
    /// </summary>
    public class Preference
    {
        private readonly DataHelper _dataHelper = new DataHelper();

        private int _id;
        private string _value;
        public string Value
        {
            get { return _value; }
        }

        public void GetValue(string preferenceName)
        {
            _dataHelper.Initialize();
            _dataHelper.Add("PrefName", preferenceName, 100);
            System.Collections.Hashtable preference =
                _dataHelper.Load("smartproject_GetPreference");
            _value = (string)preference["PrefValue"];
            _id = Convert.ToInt32(preference["PreferenceId"]);
        }

        /// <summary>
        /// Adds or Updates a preference value based on whether the preference Name
        /// exists.
        /// </summary>
        /// <param name="preferenceName">Preference name.</param>
        /// <param name="preferenceValue">Preference value.</param>
        public void Save(string preferenceName, string preferenceValue)
        {
            GetValue(preferenceName);
            bool isNew = String.IsNullOrEmpty(_value);
            _dataHelper.Initialize();
            _dataHelper.Add("PrefValue", preferenceValue, 200);
            if (isNew)
            {
                _dataHelper.Add("PrefName", preferenceName, 100);
                _dataHelper.Run("smartproject_AddPreference");
            }
            else
            {
                _dataHelper.Add("PreferenceId", _id);
                _dataHelper.Run("smartproject_UpdatePreference");
            }
        }
    }
}
